package com.ljfiction.book.MyView;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by CYS on 2017/6/25 0025.
 * 数据库操作
 */
public class DBHelper {

    private SQLiteDatabase db;
    private SqliteHelper dbHelper;

    public DBHelper(Context context) {
        dbHelper = new SqliteHelper(context);
        db = dbHelper.getWritableDatabase();
    }

    /**
     * 插入记录
     *
     * @param history_name
     * @return
     */
    public boolean insertHistory(String history_name) {
        String history = getMenu(history_name);
        if (TextUtils.isEmpty(history)) {
            ContentValues values = new ContentValues();
            values.put("history_name", history_name);
            db.insert("history", null, values);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除记录
     *
     * @param history_name
     * @return
     */
    public void deleteHistory(String history_name) {
        int menu = db.delete("history", "history_name=?", new String[]{history_name});
    }

    /**
     * 所有记录
     *
     * @return
     */
    public List<String> getAllHistory() {
        ArrayList<String> list = new ArrayList<>();
        Cursor cursor;
        cursor = db.query("history", null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            String history = cursor.getString(cursor.getColumnIndex("history_name"));
            list.add(history);
        }
        Collections.reverse(list);
        return list;
    }

    /**
     * 根据记录
     *
     * @param history_name
     * @return
     */
    private String getMenu(String history_name) {
        String history = null;
        Cursor cursor = db.query("history", null, "history_name=?", new String[]{history_name}, null, null, null);
        if (cursor.moveToNext()) {
            history = cursor.getString(cursor.getColumnIndex("history_name"));
        }
        return history;
    }

    public void close() {
        db.close();
        dbHelper.close();
    }
}
